<template>
<view class="container">
  <scroll-view class="chat_content" :style="'height:' + scrollViewHeight + 'px'" scroll-y="true" scroll-with-animation="true" :scroll-into-view="toView" @scrolltoupper="upper" @scrolltolower="lower" @click.stop="hiddenMethodsListFun">
      <!--  @scroll="scroll" -->
  <!-- bindscrolltoupper="upper" bindscrolltolower="lower" bindscroll="scroll" -->
    <block v-for="(chatMsgItem, index) in chatMsgList" :key="index">
      <chat-item-component :id="'msg_' + index" :itemId="'msg_' + index" :receiveData="chatMsgItem" :data-index="index" @resEvent="lookBigImage"></chat-item-component>
    </block>
  </scroll-view>
  <view id="bottom_send_block" :animation="inputAnimation">
  <!-- margin-bottom:{{inputBottom}}px style='bottom:{{inputBottom}}px'--> 
    <view class="bottom_send_block_left">
      <image src="https://image1.sansancloud.com/xianhua/2019_9/4/10/56/55_708.jpg?x-oss-process=style/preview_120" style="margin-left:20rpx" class="icon_block"></image>
    </view>
    <view class="bottom_send_block_center">
      <input class="input_box" type="text" :adjust-position="false" :focus="true" :value="sendValue" data-type="0" maxlength="-1" @confirm="sendOne" @focus="focusFun" @blur="blur" confirm-hold="ture" confirm-type="发送"></input>
    </view>
    <view class="bottom_send_block_right">
      <!-- <image class='icon_block' src='https://image1.sansancloud.com/xianhua/2019_9/4/11/2/9_761.jpg?x-oss-process=style/preview_120'></image>https://image1.sansancloud.com/xianhua/2019_9/6/10/21/5_125.jpg?x-oss-process=style/preview_120 -->
      <image @click.stop="sendImgFun" data-type="1" class="icon_block" src="https://image1.sansancloud.com/xianhua/2019_9/6/10/27/24_85.jpg?x-oss-process=style/preview_120"></image>
      <image @click.stop="showOtheMethodsListFun" class="icon_block" src="https://image1.sansancloud.com/xianhua/2019_9/4/11/2/9_762.jpg?x-oss-process=style/preview_120"></image>
    </view>
  </view>
  <view class="other_methods_list" :animation="otherMethodsAnimation">
    <view class="other_methods_item" v-for="(item, index) in otherMethodsList" :key="index" :data-type="item.type" @click.stop="item.handler">
      <view class="other_methods_item_img">
        <image :src="item.icon" class="other_methods_item_icon"></image>
      </view>
      <text class="other_methods_item_text">{{item.title}}</text>
    </view>
  </view>
</view>
</template>

<script>
import { socketFun } from "../../wxcomponents/public/json2Form";
var wxst;

export default {
  data() {
    return {
      chatMsgList: [],
      windowHeight: 0,
      windowWidth: 0,
      scrollViewHeight: 0,
      inputBottom: 0,
      bottomSendBlockHeight: 0,
      sendValue: '',
      rpxScalePx: 1,
      initState: true,
      toView: 'msg_0',
      inputAnimation: {},
      otherMethodsAnimation: {},
      showMethodsState: false,
      focus: false,
      otherMethodsList: [{
        icon: 'https://image1.sansancloud.com/xianhua/2019_9/6/16/5/8_273.jpg?x-oss-process=style/preview_120',
        title: '照片',
        handler: 'sendImgFun',
        type: 1
      }, {
        icon: 'https://image1.sansancloud.com/xianhua/2019_9/6/16/5/8_273.jpg?x-oss-process=style/preview_120',
        title: '照片',
        handler: 'sendImgFun',
        type: 1
      }, {
        icon: 'https://image1.sansancloud.com/xianhua/2019_9/6/16/5/8_273.jpg?x-oss-process=style/preview_120',
        title: '照片',
        handler: 'sendImgFun',
        type: 1
      }, {
        icon: 'https://image1.sansancloud.com/xianhua/2019_9/6/16/5/8_273.jpg?x-oss-process=style/preview_120',
        title: '照片',
        handler: 'sendImgFun',
        type: 1
      }, {
        icon: 'https://image1.sansancloud.com/xianhua/2019_9/6/16/5/8_273.jpg?x-oss-process=style/preview_120',
        title: '照片',
        handler: 'sendImgFun',
        type: 1
      }, {
        icon: 'https://image1.sansancloud.com/xianhua/2019_9/6/16/5/8_273.jpg?x-oss-process=style/preview_120',
        title: '照片',
        handler: 'sendImgFun',
        type: 1
      }, {
        icon: 'https://image1.sansancloud.com/xianhua/2019_9/6/16/5/8_273.jpg?x-oss-process=style/preview_120',
        title: '照片',
        handler: 'sendImgFun',
        type: 1
      }, {
        icon: 'https://image1.sansancloud.com/xianhua/2019_9/6/16/5/8_273.jpg?x-oss-process=style/preview_120',
        title: '照片',
        handler: 'sendImgFun',
        type: 1
      }],
      params: {
        page: 1
      },
      listPage: {
        pageSize: 20,
        totalSize: 0
      },
      resourceValidateInput: "",
      curPage: "",
      setting: "",
      loginUser: "",
      properties: ""
    };
  },

  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    wx.getSystemInfo({
      success: function (res) {
        console.log("===getSystemInfo===", res);
        that.setData({
          windowHeight: res.windowHeight,
          windowWidth: res.windowWidth,
          rpxScalePx: res.windowWidth / 750
        });
      }
    });
    console.log('===rpxScalePx===', that.rpxScalePx); // 然后取出navbar和header的高度
    // 根据文档，先创建一个SelectorQuery对象实例

    let query = wx.createSelectorQuery().in(that); // 然后逐个取出navbar和header的节点信息
    // 选择器的语法与jQuery语法相同

    query.select('#bottom_send_block').boundingClientRect(); // 执行上面所指定的请求，结果会按照顺序存放于一个数组中，在callback的第一个参数中返回

    query.exec(res => {
      console.log("res", res); // 分别取出navbar和header的高度

      let bottomSendBlock = res[0].height;
      console.log("bottomSendBlock", bottomSendBlock); // 然后就是做个减法

      let scrollViewHeight = that.windowHeight - bottomSendBlock; // 算出来之后存到data对象里面

      that.setData({
        scrollViewHeight: scrollViewHeight,
        bottomSendBlockHeight: bottomSendBlock,
        inputBottom: 0
      });
    });
    that.params = Object.assign({}, that.params, options);

    if (getApp().globalData.loginUser) {
      that.checkState();
    } else {
      getApp().globalData.addLoginListener(that);
      getApp().globalData.showToastLoading('loading', true);
      console.log("====setTimeout1=====");
      that.setTimeoutLogin(that.conut);
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.setData({
      setting: getApp().globalData.setting,
      properties: getApp().globalData.properties
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.reflesh == 1) {
      this.onPullDownRefresh();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    socketFun.removeListener("userChat");
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    let that = this;
    that.params.page = 1;
    that.getChatMsgList();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let that = this;

    if (that.listPage.totalSize > that.params.page * that.listPage.pageSize) {
      that.params.page++;
      getApp().globalData.showToastLoading('加载中~', true);
      that.getChatMsgList(that.params, 'addType');
    } else {
      if (that.params.page > 1) {
        wx.showToast({
          title: '到头啦~',
          image: '/wxcomponents/images/icons/tip.png',
          duration: 2000
        });
      }
    }
  },
  methods: {
    toIndex: function () {
      getApp().globalData.toIndex();
    },
    lookBigImage: function (e) {
      let that = this;
      console.log("111111111", e.currentTarget.dataset,that.chatMsgList);
      let chatMsgList = that.chatMsgList;
      let imgArray = [];
      let index = e.currentTarget.dataset.index;
      let imgIndex = 0;
      let imgId = that.chatMsgList[index].itemId||that.chatMsgList[index].id;
      let chatMsgImgList = [];
      console.log("===imgId====", imgId);

      if (that.chatMsgList[index].msgType == 1) {
        for (let i = 0; i < chatMsgList.length; i++) {
          if (chatMsgList[i].msgType == 1) {
            if (chatMsgList[i].content.indexOf("https") == -1) {
              chatMsgList[i].content = chatMsgList[i].content.replace(/http/, "https");
            }

            chatMsgImgList.push(chatMsgList[i]);
            imgArray.push(chatMsgList[i].content);
          }
        }

        for (let i = 0; i < chatMsgImgList.length; i++) {
          if (chatMsgImgList[i].id == imgId) {
            imgIndex = i;
          }
        }

        console.log("===imgIndex====", imgIndex);
        console.log(chatMsgImgList, imgArray);

        if (!chatMsgList) {
          return;
        }

        wx.previewImage({
          current: imgArray[imgIndex],
          // 当前显示图片的http链接
          urls: imgArray // 需要预览的图片http链接列表

        });
      }
    },
    upper: function () {
      console.log("====upper====");
      let that = this;
      if (that.listPage.totalSize > that.params.page * that.listPage.pageSize) {
        that.params.page++;
        getApp().globalData.showToastLoading('加载中~', true);
        that.getChatMsgList(that.params, 'addType');
      } else {
        if (that.params.page > 1) {
          wx.showToast({
            title: '到头啦~',
            image: '/wxcomponents/images/icons/tip.png',
            duration: 2000
          });
        }
      }
    },
    lower: function () {
      console.log("====lower====");
    },
    hiddenMethodsListFun: function () {
      console.log("===hiddenMethodsListFun===");
      let that = this;
      let otherMethodsAnimation = that.animationFun('bottom', 'linear', 100, '-450rpx');
      let animationData = that.animationFun('bottom', 'linear', 100, 0);
      this.setData({
        otherMethodsAnimation: otherMethodsAnimation,
        inputAnimation: animationData,
        showMethodsState: false,
        scrollViewHeight: that.windowHeight - that.bottomSendBlockHeight
      });
      // #ifdef  APP-PLUS	
          console.log("===hideKeyboard====",)
          uni.hideKeyboard()
      // #endif
    },
    showOtheMethodsListFun: function () {
      console.log("===showOtheMethodsListFun===");
      let that = this;
      let rpxScalePx = that.rpxScalePx;
      let otherMethodsAnimation = that.otherMethodsAnimation;
      let animationData = that.inputAnimation;
      let focus = that.focus;
      let showMethodsState = that.showMethodsState;
      let chatMsgList = that.chatMsgList;
      that.setData({
        showMethodsState: !showMethodsState
      });
      showMethodsState = !showMethodsState;

      if (showMethodsState) {
        otherMethodsAnimation = that.animationFun('bottom', 'linear', 100, 0);
        animationData = that.animationFun('bottom', 'linear', 100, '450rpx');
        console.log("scrollViewHeight", that.windowHeight, 450 * rpxScalePx, that.windowHeight - 450 * rpxScalePx - that.bottomSendBlockHeight);
        that.setData({
          otherMethodsAnimation: otherMethodsAnimation,
          inputAnimation: animationData,
          scrollViewHeight: that.windowHeight - 450 * rpxScalePx - that.bottomSendBlockHeight
        });
        setTimeout(function () {
          that.setData({
            toView: 'msg_' + (chatMsgList.length - 1)
          });
        }, 1000);
      } else {
        focus = true;
        otherMethodsAnimation = that.animationFun('bottom', 'linear', 100, '-450rpx'); // animationData = that.animationFun('bottom', 'linear', 100, 0)

        that.setData({
          focus: focus,
          otherMethodsAnimation: otherMethodsAnimation
        });
      }
    },
    // 发送图片
    sendImgFun: function (e) {
      console.log("====sendImgFun=====", e);
      let that = this;
      let type = e.currentTarget.dataset.type;
      socketFun.sendImgFun(type, that.params);
    },
    //发送内容
    sendOne: function (e) {
      console.log("====sendOne=====", e);
      let that = this;
      let value = e.detail.value;
      let type = e.currentTarget.dataset.type;
      that.setData({
        sendValue: value
      });

      if (value) {
        socketFun.sendMsgFun(value, type, that.params);
      } else {
        getApp().globalData.echoErr('不能发空消息~');
      }
    },

    /**
     * 获取聚焦
     */
    focusFun: function (e) {
      let that = this;
      console.log("====focus====", e, e.detail.height);
      let chatMsgList = that.chatMsgList;
      let keyHeight = e.detail.height;
      let showMethodsState = that.showMethodsState;
      let otherMethodsAnimation = that.otherMethodsAnimation;
      let scrollViewHeight=that.scrollViewHeight;
      scrollViewHeight=that.windowHeight - keyHeight - that.bottomSendBlockHeight
      console.log('====scrollViewHeight===',scrollViewHeight)
      that.setData({
        scrollViewHeight: scrollViewHeight
      });
      setTimeout(function () {
        that.setData({
          toView: 'msg_' + (chatMsgList.length - 1)
        });
      }, 1000); // 动画start

      if (showMethodsState) {
          console.log("=====控制面板存在时将面板隐藏======",)
        showMethodsState = !showMethodsState;
        otherMethodsAnimation = that.animationFun('bottom', 'linear', 100, '-450rpx');
      }
      let animationData = that.animationFun('bottom', 'linear', 100, keyHeight);
      this.setData({
        inputAnimation: animationData,
        otherMethodsAnimation: otherMethodsAnimation,
        showMethodsState: showMethodsState
      }); // 动画end
    },
    animationFun: function (type, timingFunction, time, value) {
      console.log("animationFun", type);
      let animation = wx.createAnimation({
        duration: time,
        timingFunction: timingFunction
      });
      animation[type](value).step();
      let animationData = animation.export();
      console.log("==animationData==", animationData);
      return animationData;
    },
    //失去聚焦(软键盘消失)
    blur: function (e) {
      let that = this;
      let chatMsgList = that.chatMsgList;
      let showMethodsState = that.showMethodsState;
      console.log("====blur===", e, that.windowHeight, that.bottomSendBlockHeight);
      that.setData({
        scrollViewHeight: that.windowHeight - that.bottomSendBlockHeight // inputBottom: -that.data.bottomSendBlockHeight,

      });
      setTimeout(function () {
        that.setData({
          toView: 'msg_' + (chatMsgList.length - 1)
        });
      }, 1000); // 动画start

      if (!showMethodsState) {
        let animationData = that.animationFun('bottom', 'linear', 100, 0);
        this.setData({
          inputAnimation: animationData
        });
      } // 动画end
      // #ifdef  APP-PLUS	
      console.log("===hideKeyboard====",)
      uni.hideKeyboard()
      // #endif
    },
    saveSearchValue: function (e) {
      console.log("====saveSearchValue====", e);
      let that = this;
      that.setData({
        resourceValidateInput: e.detail.value
      });
    },

    /* 获取数据 */
    setNavColor: function () {
      console.log('setNavColor', getApp().globalData.setting);
      wx.setNavigationBarColor({
        frontColor: '#000000',
        backgroundColor: '#f9f9f9'
      });
    },
    setNav: function (name) {
      console.log('setNav', getApp().globalData.setting);
      wx.setNavigationBarTitle({
        title: name
      });
    },
    getChatMsgList: function (paramData, typeState) {
      let that = this;
      let params = {
        toPlatformUserId: paramData.puid,
        page: paramData.page
      };
      that.setData({
        curPage: paramData.page,
        toView: ''
      });
      let customIndex = getApp().globalData.AddClientUrl("/wx_find_chat_msg.html", params, 'post');
      wx.request({
        url: customIndex.url,
        //仅为示例，并非真实的接口地址
        data: customIndex.params,
        header: getApp().globalData.headerPost,
        success: function (res) {
          console.log('===========getChatMsgList============', res);

          if (res.data.errcode == 0) {
            wx.hideLoading();
            console.log(res.data.relateObj);
            let resultData = res.data.relateObj.result;
            let dataList = that.chatMsgList;
            that.listPage.pageSize = res.data.relateObj.pageSize;
            that.listPage.totalSize = res.data.relateObj.totalSize;

            if (that.params.page == 1) {
              dataList = resultData.reverse();
            } else {
              for (let i = 0; i < resultData.length; i++) {
                dataList.unshift(resultData[i]);
              } // dataList = dataList.concat(resultData)

            }

            console.log("===toView===", that.toView);
            that.setData({
              chatMsgList: dataList
            }, function () {
              console.log("更新数据成功");
              let toView = '';
              setTimeout(function () {
                if (that.params.page == 1) {
                  console.log("初始化数据位置");
                  toView = 'msg_' + (dataList.length - 1);
                } else {
                  toView = 'msg_' + (resultData.length - 1);
                }

                console.log("===toView===", toView);
                that.setData({
                  toView: toView
                });
              }, 500);
            });
            console.log("===chatMsgList===", that.chatMsgList); 
            let toView = '';
            setTimeout(function () {
              if (that.params.page == 1) {
                console.log("初始化数据位置");
                toView = 'msg_' + (dataList.length - 1);
              } else {
                toView = 'msg_' + (resultData.length - 1);
              }
            
              console.log("===toView===", toView);
              that.setData({
                toView: toView
              });
            }, 2000);
            // setTimeout(function () {
            //   let toView=''
            //   if(that.params.page==1){
            //     console.log("初始化数据位置")
            //     toView = 'msg_' + that.data.chatMsgList[(dataList.length - 1)].id
            //   } else {
            //     toView = 'msg_' + that.data.chatMsgList[(resultData.length - 1)].id
            //   }
            //   console.log("===toView===", toView)
            //   that.setData({ toView: toView })
            // }, 2000)
          } else {
            console.log("接口错误");
          }
        },
        fail: function (res) {}
      });
    },
    loginSuccess: function (user) {
      console.log("pre apply mendian login success call back!", user);
      this.checkState();
    },
    loginFailed: function (err) {
      console.log("login failed!!");
    },
    checkState: function () {
      let that = this;
      console.log('======checkState.loginUser======', getApp().globalData.loginUser, getApp().globalData.socketLinkListener);
      that.setData({
        setting: getApp().globalData.setting,
        loginUser: getApp().globalData.loginUser
      });
      console.log("jhellpo!!!!!!"); // var connect = socketFun.socketConnect();

      console.log("jhellp222o!!!!!!");
      that.getChatMsgList(that.params);
      that.setNavColor();
      that.setNav(that.params.puname);

      var chatlistener = function (res) {
        console.log("===onMessage==", res);
        let chatMsgList = that.chatMsgList;
        let data = '';
        console.log("====chatMsgList=====",chatMsgList)
        try {
          data = JSON.parse(res.data);
        } catch (e) {
          data = res.data;
        }

        console.info(data);

        if (data.fromUserId == that.params.puid && data.toUserId == getApp().globalData.loginUser.platformUser.id || data.fromUserId == getApp().globalData.loginUser.platformUser.id && data.toUserId == that.params.puid) {
          res.isHandler = true;
          chatMsgList.splice(chatMsgList.length, 0, data);
          that.setData({
            chatMsgList: chatMsgList,
            sendValue: ''
          });
          setTimeout(function () {
            that.setData({
              toView: 'msg_' + (chatMsgList.length - 1)
            });
            console.log("===toView==", that.toView);
          }, 1000);
        }

        console.log("===toView==", that.toView);
        var nextListenerHandlerNextMsg = false;
        return nextListenerHandlerNextMsg;
      };

      console.log("====chatlistener=====", chatlistener); // var connect = socketFun.socketConnect(app);

      socketFun.addListener("chat", "userChat", chatlistener, 9999);
    },
    setTimeoutLogin: function (conuData) {
      let that = this;
      console.log("====setTimeout-init=====", conuData);
      that.conut = conuData;
      that.conut += 2;

      if (that.conut <= 5) {
        setTimeout(function () {
          if (getApp().globalData.loginUser) {
            wx.hideLoading();
          } else {
            that.setTimeoutLogin(that.conut);
          }
        }, that.conut * 1000);
      } else {
        wx.showModal({
          title: '失败了',
          content: '请求失败了，请下拉刷新！'
        });
      }
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
@import "./index.css";
</style>